﻿namespace DepartmentSpecificStoreView.DepartmentSpecificStoreView
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using Microsoft.SharePoint;

    public partial class DepartmentSpecificStoreViewUserControl : UserControl
    {
        #region Fields

        List<UIGridInfo> baseColumnWidthList = new List<UIGridInfo>( );
        List<UIGridInfo> columnWidthList = new List<UIGridInfo>( );
        private int commentsFieldsIndexPosition = -1;

        #endregion Fields

        #region Properties

        public string DisplayText
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        protected void activeOnly_CheckedChanged( object sender, EventArgs e )
        {
            string siteURL = SPContext.Current.Web.Url;
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                DepartmentInformationBL departments = new DepartmentInformationBL( );
                List<DepartmentViewReferences> uniqueDataAccess = new List<DepartmentViewReferences>( );

                filterValueInput.Text = "";
                ClearFilter( );
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    uniqueDataAccess = departments.SelectUniqueColumnDepartmentsValues( storeWeb, sourceDepartment.SelectedItem.Text );

                    foreach ( DepartmentViewReferences deptDataPull in uniqueDataAccess )
                        deptDataPull.PopulateCurrentDataCollection( storeWeb );

                    CreateGrid( storeWeb, uniqueDataAccess, activeOnly.Checked );
                    PopulateFieldsFilter( );
                }
            }
        }

        protected void clearFilter_Click( object sender, EventArgs e )
        {
            ClearFilter( );
        }

        protected void filterButton_Click( object sender, EventArgs e )
        {
            ApplyFilter( );
        }

        protected void Page_Load( object sender, EventArgs e )
        {
            if ( !this.IsPostBack )
            {
                string siteURL = SPContext.Current.Web.Url;
                using ( SPSite storeSite = new SPSite( siteURL ) )
                {
                    using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                    {
                        DepartmentInformationBL departments = new DepartmentInformationBL( );
                        List<DepartmentInformation> departmentListInformation = new List<DepartmentInformation>( );
                        List<DepartmentViewReferences> uniqueDataAccess = new List<DepartmentViewReferences>( );
                        BaseProjectBL baseProject = new BaseProjectBL( );

                        departments.LoadDepartments( storeWeb );
                        baseColumnWidthList = baseProject.LoadBaseColumnWidth( storeWeb );
                        ViewState[ "BaseColumnWidth" ] = baseColumnWidthList;

                        storeWeb.AllowUnsafeUpdates = true;

                        for ( int i = departments.DepartmentList.Count - 1; i >= 0; i-- )
                            if ( !CheckIfUserIsAGroupMember( departments.DepartmentList[ i ].DepartmentName ) )
                                departments.DepartmentList.Remove( departments.DepartmentList[ i ] );

                        departmentListInformation = departments.DepartmentList;
                        sourceDepartment.DataSource = departmentListInformation;
                        sourceDepartment.DataTextField = "DepartmentName";
                        sourceDepartment.DataValueField = "DepartmentCode";
                        sourceDepartment.DataBind( );

                        if ( Request[ "currentDepartment" ] != null )
                        {
                            sourceDepartment.ClearSelection( );
                            sourceDepartment.Items.FindByText( Request[ "currentDepartment" ].ToString( ) ).Selected = true;
                        }
                        uniqueDataAccess = departments.SelectUniqueColumnDepartmentsValues( storeWeb, sourceDepartment.SelectedItem.Text );

                        foreach ( DepartmentViewReferences deptDataPull in uniqueDataAccess )
                            deptDataPull.PopulateCurrentDataCollection( storeWeb );

                        bool activeOnly = true;
                        if ( Request[ "activeOnly" ] != null )
                            if ( !Request[ "activeOnly" ].ToString( ).Trim( ).Equals( string.Empty ) )
                                activeOnly = false;

                        CreateGrid( storeWeb, uniqueDataAccess, activeOnly );

                        PopulateFieldsFilter( );
                        if ( Request[ "currentSortValue" ] != null )
                            if ( !Request[ "currentSortValue" ].ToString( ).Trim( ).Equals( string.Empty ) )
                            {
                                ViewState[ "CurrentField" ] = Request[ "currentSortValue" ].ToString( );
                                ViewState[ "CurrentDirection" ] = Request[ "currentSortDirection" ].ToString( );
                            }

                        if ( Request[ "currentFilterValue" ] != null )
                            if ( !Request[ "currentFilterValue" ].ToString( ).Trim( ).Equals( string.Empty ) )
                            {
                                currentFilterFields.ClearSelection( );
                                currentFilterFields.Items.FindByText( Request[ "currentFilter" ].ToString( ) ).Selected = true;
                                filterValueInput.Text = Request[ "currentFilterValue" ].ToString( );
                            }

                        ViewState[ "ColumnWidth" ] = columnWidthList;

                        ApplyFilter( );

                        storeWeb.AllowUnsafeUpdates = true;
                    }
                }
            }
        }

        protected void RowDataBoundEvent( object sender, GridViewRowEventArgs e )
        {
            UIGridInfo singleColumn = new UIGridInfo( );
            UIGridInfo singleBaseColumn = new UIGridInfo( );
            int currentIdex = 0;

            if ( ViewState[ "BaseColumnWidth" ] != null )
                baseColumnWidthList = ( List<UIGridInfo> ) ViewState[ "BaseColumnWidth" ];

            for ( int i = 0; i < e.Row.Cells.Count; i++ )
            {
                switch ( i )
                {
                    case 0:
                        //edit
                        singleBaseColumn = baseColumnWidthList.Find( delegate( UIGridInfo sc )
                        {
                            return sc.BaseColumnName.ToString( ) == "Edit";
                        } );
                        e.Row.Cells[ i ].Width = singleBaseColumn.ColumnWidth;
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    case 1:
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    case 2:
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    case 3:
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    case 4:
                        singleBaseColumn = baseColumnWidthList.Find( delegate( UIGridInfo sc )
                        {
                            return sc.BaseColumnName.ToString( ) == "Project";
                        } );

                        e.Row.Cells[ i ].Width = singleBaseColumn.ColumnWidth;
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    case 5:
                        singleBaseColumn = baseColumnWidthList.Find( delegate( UIGridInfo sc )
                        {
                            return sc.BaseColumnName.ToString( ) == "Title";
                        } );
                        e.Row.Cells[ i ].Width = singleBaseColumn.ColumnWidth;
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    case 6:
                        singleBaseColumn = baseColumnWidthList.Find( delegate( UIGridInfo sc )
                        {
                            return sc.BaseColumnName.ToString( ) == "State";
                        } );
                        e.Row.Cells[ i ].Width = singleBaseColumn.ColumnWidth;
                        e.Row.Cells[ i ].CssClass = "locked";
                        break;
                    default:
                        currentIdex = i - 6;
                        if ( ViewState[ "ColumnWidth" ] != null )
                            columnWidthList = ( List<UIGridInfo> ) ViewState[ "ColumnWidth" ];
                        singleColumn = columnWidthList.Find( delegate( UIGridInfo sc )
                        {
                            return sc.ColumnOrder == currentIdex;
                        } );

                        e.Row.Cells[ i ].Width = singleColumn.ColumnWidth;
                        break;
                }
            }
        }

        protected void SortLocalColumn( object sender, GridViewSortEventArgs e )
        {
            DataTable dt = new DataTable( );
            string fullSortExpression = "";
            string fullFilterExpression = "";
            DataView dv;
            string currentField = ViewState[ "CurrentField" ].ToString( ).Trim( );
            if ( ViewState[ "CurrentDataViewSource" ] == null )
            {
                dt = ( DataTable ) ViewState[ "CurrentGridSource" ];

                dv = new DataView( dt );
            }
            else
            {
                dt = ( DataTable ) ViewState[ "CurrentGridSource" ];

                dv = new DataView( dt );
                fullFilterExpression = ViewState[ "CurrentDataViewSource" ].ToString( );
                dv.RowFilter = fullFilterExpression;
            }

            if ( !e.SortExpression.Trim( ).Equals( currentField ) )
            {
                currentField = e.SortExpression;
                fullSortExpression = e.SortExpression + " ASC";
                ViewState[ "CurrentDirection" ] = "ASC";
                ViewState[ "CurrentField" ] = e.SortExpression;
            }
            else
            {
                if ( ViewState[ "CurrentDirection" ].ToString( ).Trim( ).Equals( "ASC" ) )
                {
                    currentField = e.SortExpression;
                    fullSortExpression = e.SortExpression + " DESC";
                    ViewState[ "CurrentDirection" ] = "DESC";
                    ViewState[ "CurrentField" ] = e.SortExpression;
                }
                else
                {
                    currentField = e.SortExpression;
                    fullSortExpression = e.SortExpression + " ASC";
                    ViewState[ "CurrentDirection" ] = "ASC";
                    ViewState[ "CurrentField" ] = e.SortExpression;
                }
            }

            dv.Sort = fullSortExpression;

            commentsFieldsIndexPosition = -1;
            for ( int i = 0; i < departmentGridView.Columns.Count; i++ )
            {
                if ( departmentGridView.Columns[ i ].HeaderText.Trim( ).StartsWith( "Comments" ) )
                {
                    commentsFieldsIndexPosition = i;
                    break;
                }
            }
            departmentGridView.DataSource = dv;
            departmentGridView.DataBind( );

            string editURL = "";
            foreach ( GridViewRow gridRow in departmentGridView.Rows )
            {
                editURL = ( ( HyperLink ) gridRow.Cells[ 0 ].Controls[ 0 ] ).NavigateUrl;
                ( ( HyperLink ) gridRow.Cells[ 0 ].Controls[ 0 ] ).NavigateUrl = editURL + "%26currentFilterValue=" + filterValueInput.Text.Trim( ) + "%26currentFilter=" + currentFilterFields.SelectedItem.Text.Trim( ) + "%26currentSortValue=" + ViewState[ "CurrentField" ].ToString( ) + "%26currentSortDirection=" + ViewState[ "CurrentDirection" ].ToString( );

            }
        }

        protected void sourceDepartmentChanged( object sender, EventArgs e )
        {
            string siteURL = SPContext.Current.Web.Url;
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                DepartmentInformationBL departments = new DepartmentInformationBL( );
                List<DepartmentViewReferences> uniqueDataAccess = new List<DepartmentViewReferences>( );
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    uniqueDataAccess = departments.SelectUniqueColumnDepartmentsValues( storeWeb, sourceDepartment.SelectedItem.Text );

                    foreach ( DepartmentViewReferences deptDataPull in uniqueDataAccess )
                    {
                        deptDataPull.PopulateCurrentDataCollection( storeWeb );

                    }
                    CreateGrid( storeWeb, uniqueDataAccess, true );
                    PopulateFieldsFilter( );
                }
            }
        }

        private static bool CheckIfUserIsAGroupMember( string groupName )
        {
            bool result = true;

            SPSecurity.RunWithElevatedPrivileges( delegate( )
            {
                SPWeb webContext = SPContext.Current.Web;

                using ( SPSite site = new SPSite( webContext.Site.ID ) )
                {
                    using ( SPWeb web = site.OpenWeb( webContext.ID ) )
                    {
                        try
                        {
                            SPUser user = web.SiteGroups[ groupName ].Users.GetByID( SPContext.Current.Web.CurrentUser.ID );

                            if ( user != null )
                            {
                                if ( user.Groups.Count > 0 )
                                    result = true;
                                else
                                    result = false;
                            }
                            else
                                result = false;
                        }
                        catch
                        {
                            result = false;
                        }
                    }
                }
            } );

            return result;
        }

        private void ApplyFilter( )
        {
            DataTable dt = new DataTable( );
            dt = ( DataTable ) ViewState[ "CurrentGridSource" ];

            string editURL = "";
            string fullSortExpression = "";
            DataView dv = new DataView( dt );

            if ( ViewState[ "CurrentField" ] != null )
                if ( !ViewState[ "CurrentField" ].ToString( ).Equals( string.Empty ) )
                    fullSortExpression = ViewState[ "CurrentField" ].ToString( ) + " " + ViewState[ "CurrentDirection" ].ToString( );

            dv.Sort = fullSortExpression;

            dv.RowFilter = "[" + currentFilterFields.SelectedItem.Text.Trim( ) + "] LIKE '" + filterValueInput.Text.Trim( ) + "%'";

            commentsFieldsIndexPosition = -1;
            for ( int i = 0; i < departmentGridView.Columns.Count; i++ )
            {
                if ( departmentGridView.Columns[ i ].HeaderText.Trim( ).StartsWith( "Comments" ) )
                {
                    commentsFieldsIndexPosition = i;
                    break;
                }
            }

            departmentGridView.DataSource = dv;
            departmentGridView.DataBind( );

            foreach ( GridViewRow gridRow in departmentGridView.Rows )
            {
                editURL = ( ( HyperLink ) gridRow.Cells[ 0 ].Controls[ 0 ] ).NavigateUrl;

                ( ( HyperLink ) gridRow.Cells[ 0 ].Controls[ 0 ] ).NavigateUrl = editURL + "%26currentFilterValue=" + filterValueInput.Text.Trim( ) + "%26currentFilter=" + currentFilterFields.SelectedItem.Text.Trim( ) + "%26currentSortValue=" + ViewState[ "CurrentField" ].ToString( ) + "%26currentSortDirection=" + ViewState[ "CurrentDirection" ].ToString( );
            }

            ViewState[ "CurrentDataViewSource" ] = currentFilterFields.SelectedItem.Text.Trim( ) + " LIKE '" + filterValueInput.Text.Trim( ) + "%'";
        }

        private void ClearFilter( )
        {
            filterValueInput.Text = "";
            DataTable dt = new DataTable( );
            ViewState[ "CurrentDataViewSource" ] = "";
            ViewState[ "CurrentDirection" ] = "";
            ViewState[ "CurrentField" ] = "";
            dt = ( DataTable ) ViewState[ "CurrentGridSource" ];

            commentsFieldsIndexPosition = -1;
            for ( int i = 0; i < departmentGridView.Columns.Count; i++ )
            {
                if ( departmentGridView.Columns[ i ].HeaderText.Trim( ).StartsWith( "Comments" ) )
                {
                    commentsFieldsIndexPosition = i;
                    break;
                }
            }

            departmentGridView.DataSource = dt;
            departmentGridView.DataBind( );
        }

        private void CreateGrid( SPWeb storeWeb, List<DepartmentViewReferences> uniqueDataAccess, bool activeOnly )
        {
            DataTable dt = new DataTable( );
            DataRow dataRow;

            dt = DataDisplayProcess.CreateColumns( );
            string siteURL = SPContext.Current.Web.Url;

            string listName = "";

            if ( sourceDepartment.SelectedIndex == -1 )
                return;
            else
                listName = sourceDepartment.SelectedItem.Text.Trim( );

            dt = DataDisplayProcess.CreateBaseDepartmentSpecificColumns( dt, storeWeb, sourceDepartment.SelectedItem.Text );

            DepartmentInformationBL deptListInfo = new DepartmentInformationBL( );

            BaseProjectBL projectProcessing = new BaseProjectBL( );
            projectProcessing.LoadAllStores( storeWeb, listName, activeOnly );
            int q = 0;
            bool currentWidthInfo = true;
            foreach ( BaseProjectInfo baseProject in projectProcessing.StoreList )
            {
                dataRow = dt.NewRow( );
                dataRow[ "Edit Link" ] = projectProcessing.GetDepartmentRecordID( storeWeb, baseProject.Project, listName );
                dataRow[ "ListName" ] = baseProject.Listname;
                dataRow[ "ListGUID" ] = baseProject.ListGUID;
                dataRow[ "Project" ] = baseProject.Project;
                dataRow[ "State" ] = baseProject.State;
                dataRow[ "Title" ] = baseProject.Title;

                deptListInfo.GetAllListRowDataFromCollection( ref dataRow, storeWeb, baseProject.Project, listName, uniqueDataAccess, currentWidthInfo );
                currentWidthInfo = false;
                dt.Rows.Add( dataRow );
                q++;
            }

            columnWidthList = deptListInfo.UiGridWidth;

            departmentGridView.Columns.Clear( );
            string[ ] arr1 = new string[ ] { "Edit Link", "ListName", "ListGUID", "Project" };
            string editURL = "";
            HyperLinkField editLink = new HyperLinkField( );
            editLink.DataNavigateUrlFields = arr1;

            editURL = siteURL + "/Lists/{1}/FullEditForm.aspx?ID={0}&List={2}&ProjectID={3}&Source=" + siteURL + "/Store%20Pages/GridView.aspx?currentDepartment={1}";

            editLink.DataNavigateUrlFormatString = editURL;

            editLink.Text = "Edit";
            DataControlField linkControlField = editLink;
            departmentGridView.Columns.Add( linkControlField );
            if ( dt == null )
                return;
            BoundField bd = null;

            foreach ( DataColumn col in dt.Columns )
            {
                bd = new BoundField( );
                if ( col.ColumnName.Trim( ).StartsWith( "Comments" ) )
                    bd.HtmlEncode = false;
                bd.DataField = col.ColumnName;
                bd.HeaderText = col.ColumnName;
                bd.SortExpression = col.ColumnName;

                DataControlField dcf = bd;
                if ( col.ColumnName.Trim( ).Equals( "Edit Link" ) ||
                    col.ColumnName.Trim( ).Equals( "ListName" ) ||
                    col.ColumnName.Trim( ).Equals( "ListGUID" ) )
                {
                    dcf.Visible = false;
                }
                if ( col.DataType == Type.GetType( "System.DateTime" ) )
                    bd.DataFormatString = "{0:M/dd/yyyy}";
                departmentGridView.Columns.Add( dcf );
            }

            commentsFieldsIndexPosition = -1;
            for ( int i = 0; i < departmentGridView.Columns.Count; i++ )
            {
                if ( departmentGridView.Columns[ i ].HeaderText.Trim( ).StartsWith( "Comments" ) )
                {
                    commentsFieldsIndexPosition = i;
                    break;
                }
            }
            ViewState[ "ColumnWidth" ] = columnWidthList;

            departmentGridView.AutoGenerateColumns = false;
            departmentGridView.Style.Add( "table-layout", "fixed" );
            departmentGridView.DataSource = dt;
            departmentGridView.DataBind( );

            ViewState[ "CurrentGridSource" ] = dt;
            ViewState[ "CurrentField" ] = "";
            ViewState[ "CurrentDirection" ] = "ASC";

            return;
        }

        private void PopulateFieldsFilter( )
        {
            DataTable dt = new DataTable( );
            dt = ( DataTable ) ViewState[ "CurrentGridSource" ];

            DataView dv = new DataView( dt );

            DataView currentView = dv;
            if ( currentView == null )
                return;
            currentFilterFields.Items.Clear( );
            foreach ( DataColumn currentColumn in currentView.Table.Columns )
            {
                if ( !currentColumn.ColumnName.Trim( ).Equals( "Edit Link" ) &&
                    !currentColumn.ColumnName.Trim( ).Equals( "ListName" ) &&
                    !currentColumn.ColumnName.Trim( ).Equals( "ListGUID" ) )
                    currentFilterFields.Items.Add( new ListItem( currentColumn.ColumnName, currentColumn.ColumnName ) );
            }
            return;
        }

        #endregion Methods
    }
}